package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.aistar.pojo.Product;
import tech.aistar.service.ProductService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/products")
@CrossOrigin(origins = "*") // 允许跨域请求
public class ProductController {

    @Autowired
    private ProductService productService;

    // 搜索商品接口
    @GetMapping("/search/{id}")
    public ResponseEntity<Map<String, Object>> searchProduct(@PathVariable Integer id) {
        Map<String, Object> response = new HashMap<>();
        try {
            Product product = productService.searchById(id);
            if (product != null) {
                response.put("success", true);
                response.put("data", product);
                response.put("message", "商品查找成功");
            } else {
                response.put("success", false);
                response.put("message", "未找到对应的商品");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "搜索失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取所有商品接口（用于推荐商品）
    @GetMapping("/recommend")
    public ResponseEntity<Map<String, Object>> getRecommendProducts() {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Product> products = productService.findAll();
            response.put("success", true);
            response.put("data", products);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取推荐商品失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取单个商品详情
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getProduct(@PathVariable Integer id) {
        Map<String, Object> response = new HashMap<>();
        try {
            Product product = productService.findById(id);
            if (product != null) {
                response.put("success", true);
                response.put("data", product);
            } else {
                response.put("success", false);
                response.put("message", "商品不存在");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取商品失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}